using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing.Design;
using dialogs = Sixeyed.CacheAdapter.Management.Dialogs;
using System.Windows.Forms.Design;
using System.ComponentModel;
using System.Windows.Forms;
using Sixeyed.CacheAdapter.Interfaces;
using Sixeyed.CacheAdapter.Management.Dialogs;

namespace Sixeyed.CacheAdapter.Management.UITypeEditors.Bases
{
    /// <summary>
    /// Base class for UITypeEditor modal dialogs
    /// </summary>
    /// <typeparam name="TForm">Type of dialog form to load</typeparam>
    public abstract class CacheProviderEditorBase<TForm> : UITypeEditor
        where TForm : Form, new()
    {
        private IWindowsFormsEditorService service = null;
        private TForm dialog;

        /// <summary>
        /// Gets the value from the editor
        /// </summary>
        /// <returns>Value</returns>
        protected abstract object GetValue();

        /// <summary>
        /// Sets the editor value
        /// </summary>
        /// <param name="value">Value</param>
        protected abstract void SetValue(object value);

        /// <summary>
        /// Returns the edit style - modal for known contexts
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
        {
            if (null != context && null != context.Instance)
            {
                return UITypeEditorEditStyle.Modal;
            }
            return base.GetEditStyle(context);
        }

        /// <summary>
        /// Edits the value by loading the dialog form and returning the result
        /// </summary>
        /// <param name="context"></param>
        /// <param name="provider"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            if (value != null)
            {
                SetValue(value);
            }

            if (null != context && null != context.Instance && null != provider)
            {
                this.service = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
                if (null != this.service)
                {
                    this.dialog = new TForm();
                    if (this.service.ShowDialog(this.dialog) == DialogResult.OK)
                    {
                        value = GetValue();
                    }
                }
            }
            return value;
        }

        private void Exit(object sender, EventArgs e)
        {
            if (null != this.service)
            {
                this.service.CloseDropDown();
            }
        }
    }
}
